import {
  Controller,
  Get,
  Post,
  Param,
  Query,
  Request,
  Body,
} from '@nestjs/common';
import { ProductsService } from './products.service';
import { Products } from '../entities/products.entity';

@Controller('products')
export class ProductsController {
  // this.productsService = new ProductsService() 等价于 constructor 方式
  constructor(private productsService: ProductsService) {}

  @Get()
  getProductsList(): any {
    return this.productsService.getProductsList();
  }

  // get请求 -- 带参数
  // http://localhost:3000/api/products/getProductsById?id=3
  @Get('/getProductsById')
  getProductsById(@Query() query): any {
    const id: number = parseInt(query.id);
    return this.productsService.getProductsById(id);
  }

  // Get请求-@Request()装饰器-动态参数id
  // http://localhost:3000/api/products/getProductsByIdRouter/1
  @Get('/getProductsByIdRouter/:id')
  getProductsByIdRouter(@Request() req): any {
    const id: number = parseInt(req.params.id);
    return this.productsService.getProductsByIdRouter(id);
  }

  // Get请求-@Param()装饰器-动态参数id，name
  // http://localhost:3000/api/products/getProductsByIdRouter/1/huawei-mate-60
  @Get('/getProductsByIdRouter/:id/:name')
  getProductsByIdRouter2(@Param() Params): any {
    const id: number = parseInt(Params.id);
    const name: string = Params.name;
    return this.productsService.getProductsByIdRouter2(id, name);
  }

  // post请求
  // http://localhost:3000/api/products/addProducts
  @Post('/addProducts')
  addProducts(): any {
    return this.productsService.addProducts();
  }

  // post请求 -- 带参数
  @Post('/addPostProducts')
  addPostProducts(@Body() body): any {
    const id = body.id;
    return this.productsService.addPostProducts(id);
  }

  // 通过数据库查询产品list
  @Get('list')
  getList(): Promise<Products[]> {
    return this.productsService.getList();
  }
}
